package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.AuthorizationDetail;
import com.colorlight.cloud.complete.entity.po.DeviceAuthResultInfo;
import com.colorlight.cloud.complete.entity.po.SenderAuthResultInfo;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 解密指令
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class Decrypt implements CompleteEntityScheduleActions {

	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	public static class InputMsg implements Serializable {
		/**
		 * 授权详情
		 */
		private AuthorizationDetail detail;
	}

	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	public static class OutputMsg implements Serializable {
		/**
		 * 设备授权结果信息
		 */
		private DeviceAuthResultInfo deviceAuthResultInfo;
		/**
		 * 发送器授权结果信息列表
		 */
		private List<SenderAuthResultInfo> senderAuthResultInfo;
	}

	private InputMsg input;
	private OutputMsg output;

	@Override
	public ByteString objectConvertBytes() {
		final CompleteInstruction.Decrypt.InputMsg.Builder inputMsg =
				CompleteInstruction.Decrypt.InputMsg.newBuilder();
		Decrypt.InputMsg thisInput = this.getInput();
		inputMsg.setDetail(thisInput.getDetail().toProto());
		final CompleteInstruction.Decrypt.Builder builder =
				CompleteInstruction.Decrypt.newBuilder();
		builder.setInput(inputMsg);
		return builder.build().toByteString();
	}

	@Override
	public Decrypt byteConvertObject(ByteString bytes) {
		CompleteInstruction.Decrypt decrypt = null;
		try {
			decrypt = CompleteInstruction.Decrypt.parseFrom(bytes);
		} catch (InvalidProtocolBufferException e) {
			log.error("", e);
		}
		if (Objects.isNull(decrypt)) {
			throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
		}
		Decrypt.OutputMsg outputMsg = new Decrypt.OutputMsg();
		CompleteInstruction.Decrypt.OutputMsg output = decrypt.getOutput();
		DeviceAuthResultInfo deviceAuthResultInfo = new DeviceAuthResultInfo().formProto(output.getDeviceAuthResultInfo());
		List<SenderAuthResultInfo> senderAuthResultInfo = output.getSenderAuthResultInfoList().stream()
				.map(proto -> new SenderAuthResultInfo().formProto(proto))
				.collect(Collectors.toList());
		outputMsg.setDeviceAuthResultInfo(deviceAuthResultInfo);
		outputMsg.setSenderAuthResultInfo(senderAuthResultInfo);
		this.setOutput(outputMsg);
		return this;
	}
}
